﻿using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using DevExpress.XtraEditors;
using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Wizard;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrinting.Preview;
using ContractManager.BLL.Business;

namespace ContractManager.Reports.Forms
{
    public partial class FrmPivotGrid : XtraFormBase
    {
        #region "Define Variable"
        private string _companyName = string.Empty;
        private string _companyAddress = string.Empty;
        private string _companyTel = string.Empty;
        private string _companyFax = string.Empty;
        private string _companyTelFax = string.Empty;
        private string _companyTaxCode = string.Empty;
        #endregion

        #region "Construction"
        public FrmPivotGrid()
        {
            InitializeComponent();
            ViewType[] restrictedTypes = new ViewType[] { ViewType.PolarArea, ViewType.PolarLine, ViewType.SideBySideGantt, ViewType.Bubble,
				ViewType.SideBySideRangeBar, ViewType.RangeBar, ViewType.Gantt, ViewType.PolarPoint, ViewType.Stock, ViewType.CandleStick,
                ViewType.SideBySideFullStackedBar, ViewType.SideBySideFullStackedBar3D, ViewType.SideBySideStackedBar, ViewType.SideBySideStackedBar3D };
            foreach (ViewType type in Enum.GetValues(typeof(ViewType)))
            {
                if (Array.IndexOf<ViewType>(restrictedTypes, type) >= 0) continue;
                comboChartType.Properties.Items.Add(type);
            }
            comboChartType.SelectedItem = ViewType.Line;
        }
        #endregion

        #region "Private Method"

        //private void GetCompany()
        //{
            
        //    _objReport.ReportGetCompanyInfo(ref _companyName, ref _companyAddress, ref _companyTelFax, ref _companyTaxCode, ref _companyTel, ref _companyFax);
        //}

        private void BankForm()
        {
            txtMbId.Properties.DataSource = ClsMemberBranch.SelectAll();
            txtMbId.Properties.DisplayMember = "MbName";
            txtMbId.Properties.ValueMember = "MbID";    
        }

        private void DoPerform()
        {
            try
            {
                string mbId = String.Format("{0}", txtMbId.EditValue);

                DataTable dtReport = ClsReports.GetReportPivotGrid(txtKyBC.FromDate, txtKyBC.ToDate, mbId, txtdType.SelectedIndex, this.StoreProcedureName);
                pivotGridControl.DataSource = dtReport;
                pivotGridControl.RetrieveFields();
                string strfilename = String.Format(@"{0}\Layout\{1}", Application.StartupPath,this.ReportName);
                if (File.Exists(strfilename))
                {
                    pivotGridControl.RestoreLayoutFromXml(strfilename, DevExpress.Utils.OptionsLayoutBase.FullLayout);    
                }
                pivotGridControl.OptionsView.ShowRowHeaders = true;
                pivotGridControl.OptionsView.ShowColumnHeaders = true;
                pivotGridControl.OptionsView.ShowDataHeaders = true;
                pivotGridControl.OptionsView.ShowFilterHeaders = true;
                //Point[] selection = new Point[pivotGridControl.Cells.ColumnCount * 2];
                //for (int i = 0; i < pivotGridControl.Cells.ColumnCount; i++)
                //{
                //    selection[i] = new Point(i, 0);
                //    selection[i + pivotGridControl.Cells.ColumnCount] = new Point(i, 2);
                //}
                //pivotGridControl.Cells.MultiSelection.SetSelection(selection);
                //pivotGridControl.BestFitRowArea();
                pivotGridControl.BestFit();
                chartControl.DataSource = pivotGridControl;
                chartControl.SeriesTemplate.Label.Visible = checkShowPointLabels.Checked;
                chartControl.Legend.AlignmentHorizontal = LegendAlignmentHorizontal.Left;
                chartControl.Legend.AlignmentVertical = LegendAlignmentVertical.TopOutside;
                chartControl.Legend.Direction = LegendDirection.RightToLeft;
            }
            catch (Exception ex)
            {
                
                XtraMessageBox.Show(
                    "Có lỗi xảy ra trong quá trình in báo cáo " + ex.Message,
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }

        }

       
        #endregion

        #region "Form Event"
        private void frmBaoCaoPhanTich_Load(object sender, EventArgs e)
        {
            txtKyBC.Year = ClsVariable.Year;
            txtKyBC.SelectIndex = 7;
            txtdType.SelectedIndex = 0;
            BankForm();
            propertyGridControl.SelectedObject = pivotGridControl;
            txtReportTemplate.Text = this.Text;
        }
        #endregion

        #region "Button Event"

        private void btnOk_Click(object sender, EventArgs e)
        {
            DoPerform();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            saveFileDialog.ShowDialog();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            openFileDialog.ShowDialog();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            PrintPreviewRibbonFormEx previewForm = new PrintPreviewRibbonFormEx();
            PrintingSystem printingSystem1 = new PrintingSystem();

            DevExpress.XtraPrintingLinks.CompositeLink compositeLink = new DevExpress.XtraPrintingLinks.CompositeLink() { PrintingSystem = printingSystem1 };
            compositeLink.CreateReportHeaderArea += new CreateAreaEventHandler(compositeLink_CreateReportHeaderArea);
            compositeLink.CreateReportFooterArea += new CreateAreaEventHandler(compositeLink_CreateReportFooterArea);
            PrintableComponentLink link = new PrintableComponentLink();
            pivotGridControl.OptionsView.ShowDataHeaders = false;
            pivotGridControl.OptionsView.ShowFilterHeaders = false;
            pivotGridControl.OptionsView.ShowColumnHeaders = false;
            link.Component = pivotGridControl;
            compositeLink.Links.Add(link);

            //link = new PrintableComponentLink() { Component = chartControl };
            //compositeLink.Links.Add(link);
            compositeLink.ShowPreview();
            pivotGridControl.OptionsView.ShowColumnHeaders = true;
            pivotGridControl.OptionsView.ShowDataHeaders = true;
            pivotGridControl.OptionsView.ShowFilterHeaders = true;
        }

        private void compositeLink_CreateReportFooterArea(object sender, CreateAreaEventArgs e)
        {
            CreateReportFooter(e.Graph);
        }

        private void compositeLink_CreateReportHeaderArea(object sender, CreateAreaEventArgs e)
        {
            CreateReportHeader(e.Graph);
        }

        private void CreateReportHeader(BrickGraphics gr)
        {
            const float captionHeight = 40f;
            string documentCaption = txtReportTemplate.Text;
            string CompanyName = "test";
            float pText = 0;
            float pEmpty = 0;
            pText += gr.MeasureString(CompanyName).Height;
            //Thông tin đơn vị
            //Tên đơn vị
            gr.Font = new Font("Tahoma", 8f, FontStyle.Bold);
            gr.BorderWidth = 0f;
            VisualBrick visBrick = gr.DrawString(_companyName, new RectangleF(new PointF(5, pEmpty), new SizeF(gr.ClientPageSize.Width, 20)));
            pText += gr.MeasureString(_companyName).Height;

            //Địa chỉ
            visBrick = gr.DrawString(_companyAddress, new RectangleF(new PointF(5, pText), new SizeF(gr.ClientPageSize.Width, 20)));
            pText += gr.MeasureString(_companyAddress).Height;
            //Điện thoại
            CompanyName = String.Format("Điện thoại/Fax: {0}/{1}", _companyTel, _companyFax);
            visBrick = gr.DrawString(CompanyName, new RectangleF(new PointF(5, pText), new SizeF(gr.ClientPageSize.Width, 20)));
            pText += gr.MeasureString(CompanyName).Height;

            gr.Font = new Font("Tahoma", 12f, FontStyle.Bold);
            gr.BorderWidth = 0f;
            gr.StringFormat = gr.StringFormat
                .ChangeLineAlignment(StringAlignment.Center)
                .ChangeAlignment(StringAlignment.Center);
            // Create a text brick.
            visBrick = gr.DrawString(documentCaption, new RectangleF(new PointF(5, pText), new SizeF(gr.ClientPageSize.Width, captionHeight)));
            pText += gr.MeasureString(documentCaption).Height;
            pText += 10;
            gr.Font = new Font("Tahoma", 8f, FontStyle.Italic);
            //thay pText = 40
            //Kỳ báo cáo
            RectangleF rect = new RectangleF(new PointF(5, pText), new SizeF(gr.ClientPageSize.Width, captionHeight-10));
            visBrick = gr.DrawString(txtKyBC.KyBc, Color.Black, rect, DevExpress.XtraPrinting.BorderSide.All);
        }

        private void CreateReportFooter(BrickGraphics gr)
        {
            string strFooter = "Người lập biểu";
            gr.Font = gr.DefaultFont;
            gr.BackColor = Color.Transparent;
            gr.Modifier = BrickModifier.ReportFooter;
            RectangleF r = new RectangleF(10, 10, 250, gr.Font.Height);

            Font font = new Font("Tahoma", 8f, FontStyle.Bold);
            gr.Font = font;
            VisualBrick visBrick = gr.DrawString(strFooter, Color.Black, r, DevExpress.XtraPrinting.BorderSide.None);

            font = new Font("Tahoma", 8f, FontStyle.Italic);
            gr.Font = font;
            strFooter = "(Ký, ghi rõ họ tên)";
            r = new RectangleF(10, 30, 250, gr.Font.Height);
            visBrick = gr.DrawString(strFooter, Color.Black, r, DevExpress.XtraPrinting.BorderSide.None);
            //Kế toán trưởng
            font = new Font("Tahoma", 8f, FontStyle.Bold);
            gr.Font = font;
            strFooter = "Kế toán trưởng";
            r = new RectangleF(300, 10, 250, gr.Font.Height);
            visBrick = gr.DrawString(strFooter, Color.Black, r, DevExpress.XtraPrinting.BorderSide.None);

            font = new Font("Tahoma", 8f, FontStyle.Italic);
            gr.Font = font;
            strFooter = "(Ký, họ tên, đóng dấu)";
            r = new RectangleF(300, 30, 250, gr.Font.Height);
            visBrick = gr.DrawString(strFooter, Color.Black, r, DevExpress.XtraPrinting.BorderSide.None);


            //Giám đốc
            font = new Font("Tahoma", 8f, FontStyle.Bold);
            gr.Font = font;
            strFooter = "Giám đốc";
            r = new RectangleF(600, 10, 250, gr.Font.Height);
            visBrick = gr.DrawString(strFooter, Color.Black, r, DevExpress.XtraPrinting.BorderSide.None);

            font = new Font("Tahoma", 8f, FontStyle.Italic);
            gr.Font = font;
            strFooter = "(Ký, họ tên, đóng dấu)";
            r = new RectangleF(600, 30, 250, gr.Font.Height);
            visBrick = gr.DrawString(strFooter, Color.Black, r, DevExpress.XtraPrinting.BorderSide.None);
        }
        #endregion


        #region "Dialog Event"
        private void saveFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            string strfilename = saveFileDialog.FileName;
            string strExtension = Path.GetExtension(strfilename).Substring(1);
            switch (strExtension)
            {
                case "xml":
                    pivotGridControl.SaveLayoutToXml(strfilename, DevExpress.Utils.OptionsLayoutBase.FullLayout);
                    break;
            }
        }

        private void openFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            string strfilename = openFileDialog.FileName;
            pivotGridControl.RestoreLayoutFromXml(strfilename,DevExpress.Utils.OptionsLayoutBase.FullLayout);
        }

        private void saveFileExportDialog_FileOk(object sender, CancelEventArgs e)
        {
            string strfilename = saveFileExportDialog.FileName;
            string strExtension = Path.GetExtension(strfilename).Substring(1);
            switch (strExtension)
            {
                case "pdf":
                    pivotGridControl.ExportToPdf(strfilename);
                    break;
                case "rtf":
                    pivotGridControl.ExportToRtf(strfilename);
                    break;
                case "xls":
                    pivotGridControl.ExportToXls(strfilename);
                    break;
                case "xlsx":
                    pivotGridControl.ExportToXlsx(strfilename);
                    break;
            }
        }
        #endregion

        #region "Toolbar Event"

        private void tbMenu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                default:
                    saveFileExportDialog.ShowDialog();
                    break;
            }
        }
        #endregion

        #region "Combo Chart Control Event"
        private void comboChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            chartControl.SeriesTemplate.ChangeView((ViewType)comboChartType.SelectedItem);
           
        }

        private void ceChartDataVertical_CheckedChanged(object sender, EventArgs e)
        {
            pivotGridControl.OptionsChartDataSource.ProvideDataByColumns = !ceChartDataVertical.Checked;
        }

        private void ceShowPoint_CheckedChanged(object sender, EventArgs e)
        {
            chartControl.SeriesTemplate.ChangeView((ViewType)comboChartType.SelectedItem);
            if (chartControl.SeriesTemplate.Label != null)
            {
                chartControl.SeriesTemplate.Label.Visible = checkShowPointLabels.Checked;
                checkShowPointLabels.Enabled = true;
            }
            else
            {
                checkShowPointLabels.Enabled = false;
            }
            if ((chartControl.SeriesTemplate.View as SimpleDiagramSeriesViewBase) == null)
                chartControl.Legend.Visible = true;
            if (chartControl.Diagram is Diagram3D)
            {
                Diagram3D diagram = (Diagram3D)chartControl.Diagram;
                diagram.RuntimeRotation = true;
                diagram.RuntimeZooming = true;
                diagram.RuntimeScrolling = true;
            }
            foreach (Series series in chartControl.Series)
            {
                ISupportTransparency supportTransparency = series.View as ISupportTransparency;
                if (supportTransparency != null)
                {
                    if ((series.View is AreaSeriesView) || (series.View is Area3DSeriesView)
                        || (series.View is RadarAreaSeriesView) || (series.View is Bar3DSeriesView))
                        supportTransparency.Transparency = 135;
                    else
                        supportTransparency.Transparency = 0;
                }
            }
        }

        private void btnChartWizard_Click(object sender, EventArgs e)
        {
            ChartWizard ctwiz = new ChartWizard(chartControl);
            ctwiz.ShowDialog();
        }

        #endregion

        #region "Pivot Grid Event"
        private void pivotGridControl_CellDoubleClick(object sender, DevExpress.XtraPivotGrid.PivotCellEventArgs e)
        {
            string strWhere = String.Empty;
            PivotGridField[] rowFields = e.GetRowFields();
            PivotGridField[] columnFields = e.GetColumnFields();
            
            strWhere = rowFields.Aggregate(strWhere, (current, row) => String.Format(String.IsNullOrEmpty(current) ? "{0}='{1}'" : " AND {0}='{1}'", row.FieldName, e.GetFieldValue(e.RowField)));
            strWhere = strWhere + columnFields.Aggregate(strWhere, (current, col) => String.Format(String.IsNullOrEmpty(current) ? "{0}='{1}'" : " AND {0}='{1}'", col.FieldName, e.GetFieldValue(e.ColumnField)));
            XtraMessageBox.Show(strWhere);
        }

        private void pivotGridControl_CustomCellDisplayText(object sender, PivotCellDisplayTextEventArgs e)
        {
            if (!StoreProcedureName.Equals("usp_Report_BC12")) return;
            if (e.DataField == null) return;
            if (!e.DataField.FieldName.Equals("PerComplete")) return;
            object planAmount = null;
            object realAmount = null;

            foreach (var colField in pivotGridControl.GetFieldsByArea(PivotArea.DataArea))
            {
                if (colField.FieldName.Equals("PlanAmount"))
                {
                    planAmount = e.GetCellValue(colField);
                }
                if (colField.FieldName.Equals("RealAmount"))
                {
                    realAmount = e.GetCellValue(colField);
                }
            }

            if (planAmount == null || realAmount == null) return;
            decimal plan = Convert.ToDecimal(planAmount);
            decimal real = Convert.ToDecimal(realAmount);
            if (plan != 0)
            {
                decimal perc = real != 0 ? real / plan : 0;
                e.DisplayText = string.Format("{0:p}", perc);
            }
            else
            {
                e.DisplayText = string.Format("{0:p}", 0);
            }

        }
        #endregion

        




    }
}